<template>
  <div class="reginter">
    <div class="tab">
      <el-link type="primary" :underline="false">注册</el-link>
    </div>
    <el-form :model="registerForm" :rules="registerRules" ref="registerForm">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="registerForm.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item class="drag-verify">
        <edu-drag-verify
          ref="dragVerify"
          :height="38"
          :width="340"
          radius="2px"
          :isPassing.sync="isPassing"
          text="请按住滑块，拖动到最右边"
          successText="验证通过"
          handlerIcon="el-icon-d-arrow-right"
          successIcon="el-icon-circle-check"
          @passcallback="passcallback('registerForm')"
        ></edu-drag-verify>
      </el-form-item>
      <el-form-item prop="verify">
        <el-row type="flex" class="verifyCode">
          <el-input v-model="registerForm.verify" placeholder="请输入验证码"></el-input>
          <EduVerificationCode
            @start="getVerifyCode('registerForm')"
            :disabled="btnDisabled"
          ></EduVerificationCode>
        </el-row>
      </el-form-item>
      <el-form-item label="设置密码" prop="password">
        <el-input
          type="password"
          v-model="registerForm.password"
          placeholder="密码长度为6～20个字符"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="password2">
        <el-input
          type="password"
          v-model="registerForm.password2"
          placeholder="再次输入新密码"
        ></el-input>
      </el-form-item>
      <el-row type="flex" align="middle" class="agreement">
        <el-checkbox v-model="agreementChecked">我已阅读并同意</el-checkbox>
        <el-link :underline="false" @click="handleKeyword('userRegister')"
          >《{{ getAgreementTitle('userRegister') }}》</el-link
        >
        <el-link :underline="false" @click="handleKeyword('userPrivacy')"
          >《{{ getAgreementTitle('userPrivacy') }}》</el-link
        >
      </el-row>
      <div class="reginter-footer">
        <el-button type="primary" @click="handleRegister('registerForm')">注册</el-button>
        <el-row type="flex" align="middle">
          <span class="no-text">已有账号？</span>
          <el-link type="primary" :underline="false" @click="goLogin">去登录</el-link>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import EduDragVerify from '@/components/EduDragVerify'
import EduVerificationCode from '@/components/EduVerificationCode'
import md5 from 'spark-md5'
import store from '@/store'
import { mapGetters } from 'vuex'
export default {
  components: {
    EduDragVerify,
    EduVerificationCode
  },
  data() {
    // 手机号码的校验
    var testPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else {
        if (!this.$util.mobile(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
    }
    // 密码的验证
    var testPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (!this.$util.password(value)) {
          callback(new Error('密码格式不正确'))
        } else {
          callback()
        }
      }
    }
    // 确认密码验证
    var testUsedPassWord = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      isPassing: false,
      agreementChecked: true,
      registerForm: {
        phone: '',
        password: '',
        password2: '',
        verify: ''
      },
      registerRules: {
        phone: [{ validator: testPhone, trigger: 'blur' }],
        verify: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }
        ],
        password: [{ validator: testPassword, trigger: 'blur' }],
        password2: [{ validator: testUsedPassWord, trigger: 'blur' }]
      },
      btnDisabled: true
    }
  },
  computed: {
    loginRouteName() {
      return this.$store.getters['projectSetting/getGlobLoginRouteName']
    },
    ...mapGetters({
      getAgreementTitle: 'projectSetting/getAgreementTitle'
    })
  },
  created: function() {
    // 注册回车事件
    document.onkeydown = e => {
      var key = window.event.keyCode
      if (key == 13) {
        this.handleRegister('registerForm')
      }
    }
  },
  methods: {
    // 提交
    handleRegister(formName) {
      var that = this
      that.$refs[formName].validate(valid => {
        if (valid) {
          if (!that.agreementChecked) {
            that.$message.warning(
              '阅读并同意' +
                this.getAgreementTitle('userRegister') +
                this.getAgreementTitle('userPrivacy')
            )
          } else {
            store
              .dispatch('user/accountRegister', {
                phone: that.registerForm.phone,
                password: md5.hash(that.registerForm.password)
              })
              .then(res => {
                that.$message.success(res.msg) // 登录成功提示
                that.$emit('handleSuccess') // 登录成功返回关闭弹窗
                that.$refs[formName].resetFields() // 登录成功重置表单
              })
              .catch(error => {
                that.$message.error(error.msg)
              })
          }
        } else {
          return false
        }
      })
    },
    // 切换到登录
    goLogin() {
      this.$emit('currentTab', this.loginRouteName)
    },
    // 滑动验证通过
    passcallback(formName) {
      var that = this
      that.$refs[formName].validateField('phone', valid => {
        if (!valid) {
          this.btnDisabled = false
        } else {
          that.dragVerifyReset()
          return false
        }
      })
    },
    // 获取验证码
    getVerifyCode() {
      var that = this
      this.$api.createSmsVerify(
        { phone: that.registerForm.phone, type: 'login' },
        res => {
          that.$message.success(res.msg)
        },
        error => {
          that.$message.error(error.msg)
        }
      )
    },
    // 重置滑动验证
    dragVerifyReset() {
      var that = this
      that.isPassing = false
      that.$refs.dragVerify.reset()
    },
    handleKeyword(key) {
      let route = this.$router.resolve({
        path: '/agreement/' + key
      })
      window.open(route.href)
    }
  }
}
</script>
<style scoped>
.agreement {
  flex-wrap: wrap;
  margin-bottom: 22px;
  line-height: 1;
}
</style>
